package com.yiwei.zxp.activity;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.widget.NestedScrollView;
import android.text.TextUtils;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ScrollView;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps2d.AMap;
import com.amap.api.maps2d.CameraUpdateFactory;
import com.amap.api.maps2d.LocationSource;
import com.amap.api.maps2d.MapView;
import com.amap.api.maps2d.model.CameraPosition;
import com.amap.api.maps2d.model.LatLng;
import com.amap.api.maps2d.model.MarkerOptions;
import com.amap.api.maps2d.model.MyLocationStyle;
import com.amap.api.maps2d.overlay.PoiOverlay;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.core.PoiItem;
import com.amap.api.services.core.SuggestionCity;
import com.amap.api.services.geocoder.GeocodeAddress;
import com.amap.api.services.geocoder.GeocodeResult;
import com.amap.api.services.geocoder.GeocodeSearch;
import com.amap.api.services.geocoder.RegeocodeQuery;
import com.amap.api.services.geocoder.RegeocodeResult;
import com.amap.api.services.poisearch.PoiResult;
import com.amap.api.services.poisearch.PoiSearch;
import com.yiwei.zxp.R;
import com.yiwei.zxp.api.Api;
import com.yiwei.zxp.api.bean.AddressIdBean;
import com.yiwei.zxp.api.bean.UserEditBean;
import com.yiwei.zxp.base.BaseActivity;
import com.yiwei.zxp.event.AreaAddressEvent;
import com.yiwei.zxp.event.LoginSuccessEvent;
import com.yiwei.zxp.util.Network;
import com.yiwei.zxp.util.RxLifeUtil;
import com.yiwei.zxp.util.ToastUtil;
import com.yiwei.zxp.util.UI;
import com.yiwei.zxp.view.SelectAreaDilaog;

import org.greenrobot.eventbus.EventBus;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;


/**
 * Created by xsooy-pc on 2017/10/17.
 */

public class New_LocalActivity extends BaseActivity implements LocationSource,
        AMapLocationListener, AMap.OnCameraChangeListener, PoiSearch.OnPoiSearchListener, GeocodeSearch.OnGeocodeSearchListener, SelectAreaDilaog.OnChooseListener {
    @BindView(R.id.map_local)
    MapView mapView;
    //    @BindView(R.id.map_list)
//    ListView mapList;
    public static final String KEY_LAT = "lat";
    public static final String KEY_LNG = "lng";
    public static final String KEY_DES = "des";
    @BindView(R.id.edit_search)
    EditText editSearch;
    @BindView(R.id.txt_title)
    TextView txtTitle;
    @BindView(R.id.txt_right)
    TextView txtRight;
    @BindView(R.id.txt_area)
    TextView txtArea;
    @BindView(R.id.scrollView)
    NestedScrollView scrollView;
    private AMapLocationClient mLocationClient;
    private OnLocationChangedListener mListener;
    private LatLng latlng;
    private LatLng firstLatlng;
    private String city;
    private AMap aMap;
    private String deepType = "190000";// poi搜索类型
    private PoiSearch.Query query;// Poi查询条件类
    private PoiSearch poiSearch;
    private PoiResult poiResult; // poi返回的结果
    private PoiOverlay poiOverlay;// poi图层
    private List<PoiItem> poiItems;// poi数据
    private Unbinder unbiner;
    //    private PoiSearch_adapter adapter;
    private String searchPlace = "";
    private GeocodeSearch geocoderSearch;
    private String addressName;
    private boolean isOneLocat = true;
    private String province_id, city_id, district_id, address, lat, lng;
    private SelectAreaDilaog selectAreaDialog;
    private AreaAddressEvent event;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_new_local);
        unbiner = ButterKnife.bind(this);
        mapView.onCreate(savedInstanceState);
        init();
        //		 重写onTouch()事件,在事件里通过requestDisallowInterceptTouchEvent(boolean)方法来设置父类的不可用,true表示父类的不可用
        //解决地图的touch事件和scrollView的touch事件冲突问题
        mapView.setOnTouchListener(new View.OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (event.getAction() == MotionEvent.ACTION_UP) {
                    scrollView.setEnabled(true);
                } else {
                    scrollView.setEnabled(false);
                }
                return false;
            }
        });
        event = new AreaAddressEvent();
    }

    private void init() {
        initBar();
        txtTitle.setText("门店地址");
        txtRight.setVisibility(View.VISIBLE);
        txtRight.setText("确定");
        if (aMap == null) {
            aMap = mapView.getMap();
            aMap.setOnCameraChangeListener(this);
            setUpMap();
        }

//        deepType = "餐饮";//这里以餐饮为例
        selectAreaDialog = new SelectAreaDilaog(this).setOnChooseListener(this);
    }

    //-------- 定位 Start ------
    private void setUpMap() {
        if (mLocationClient == null) {
            mLocationClient = new AMapLocationClient(getApplicationContext());
            AMapLocationClientOption mLocationOption = new AMapLocationClientOption();
            //设置定位监听
            mLocationClient.setLocationListener(this);
            //设置为高精度定位模式
//            mLocationOption.setOnceLocation(true);
            mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
            //设置定位参数
            mLocationClient.setLocationOption(mLocationOption);
            mLocationClient.startLocation();
        }
        // 自定义系统定位小蓝点
        MyLocationStyle myLocationStyle = new MyLocationStyle();
//        myLocationStyle.myLocationIcon(BitmapDescriptorFactory
//                .fromResource(R.drawable.location_marker));// 设置小蓝点的图标
        myLocationStyle.strokeColor(Color.BLACK);// 设置圆形的边框颜色
        myLocationStyle.radiusFillColor(Color.argb(100, 0, 0, 180));// 设置圆形的填充颜色
        myLocationStyle.strokeWidth(1.0f);// 设置圆形的边框粗细
        aMap.setMyLocationStyle(myLocationStyle);
        aMap.setLocationSource(this);// 设置定位监听
        aMap.getUiSettings().setMyLocationButtonEnabled(true);// 设置默认定位按钮是否显示
        aMap.setMyLocationEnabled(true);// 设置为true表示显示定位层并可触发定位，false表示隐藏定位层并不可触发定位，默认是false
    }

    /**
     * 开始进行poi搜索
     */
    protected void doSearchQuery() {
        query = new PoiSearch.Query(searchPlace, "", city);// 第一个参数表示搜索字符串，第二个参数表示poi搜索类型，第三个参数表示poi搜索区域（空字符串代表全国）
        query.setPageSize(10);// 设置每页最多返回多少条poiitem
        query.setPageNum(0);// 设置查第一页

        poiSearch = new PoiSearch(this, query);
        poiSearch.setOnPoiSearchListener(this);
        poiSearch.searchPOIAsyn();
//        aMap.setOnMapClickListener(null);// 进行poi搜索时清除掉地图点击事件
//        int currentPage = 0;
//        Log.i("doSearchQuery", "关键字：" + searchPlace + "城市：" + city);
//        query = new PoiSearch.Query(searchPlace, "", city);// 第一个参数表示搜索字符串，第二个参数表示poi搜索类型，第三个参数表示poi搜索区域（空字符串代表全国）
//        query.setPageSize(20);// 设置每页最多返回多少条poiitem
//        query.setPageNum(currentPage);// 设置查第一页
//        LatLonPoint lp = new LatLonPoint(latlng.latitude, latlng.longitude);
//        poiSearch = new PoiSearch(this, query);
//        poiSearch.setOnPoiSearchListener(this);
//        poiSearch.setBound(new PoiSearch.SearchBound(lp, 5000, true));
//        // 设置搜索区域为以lp点为圆心，其周围2000米范围
//        poiSearch.searchPOIAsyn();// 异步搜索
    }

    //    逆地理编码
    private void doRePlace() {
        geocoderSearch = new GeocodeSearch(this);
        geocoderSearch.setOnGeocodeSearchListener(this);
        RegeocodeQuery query = new RegeocodeQuery(new LatLonPoint(latlng.latitude, latlng.longitude), 200, GeocodeSearch.AMAP);

        geocoderSearch.getFromLocationAsyn(query);

//        GeocodeSearch geocoderSearch1 = new GeocodeSearch(this);
//        geocoderSearch1.setOnGeocodeSearchListener(this);
//        GeocodeQuery geocodeQuery = new GeocodeQuery("广东省东莞市", "29");
//        geocoderSearch1.getFromLocationNameAsyn(geocodeQuery);
    }


    @Override
    public void onLocationChanged(AMapLocation aMapLocation) {
        if (mListener != null && aMapLocation != null) {
            if (aMapLocation.getErrorCode() == 0) {
                // 显示我的位置
                mListener.onLocationChanged(aMapLocation);
                //设置第一次焦点中心
                latlng = new LatLng(aMapLocation.getLatitude(), aMapLocation.getLongitude());
                firstLatlng = new LatLng(aMapLocation.getLatitude(), aMapLocation.getLongitude());
                aMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latlng, 14), 1000, null);
                city = aMapLocation.getProvince();

                lat = aMapLocation.getLatitude() + "";
                lng = aMapLocation.getLongitude() + "";

                if (isOneLocat) {
                    getAddressId(aMapLocation.getProvince(), aMapLocation.getCity(), aMapLocation.getDistrict());
                    isOneLocat = false;
                }


//                doSearchQuery();
//                Log.e("AmapErr", aMapLocation.getAddress());
            } else {
                String errText = "定位失败," + aMapLocation.getErrorCode() + ": " + aMapLocation.getErrorInfo();
//                Log.e("AmapErr", errText);
            }
        }
    }

    public void getAddressId(String province, String city, String district) {
        if (!Network.checkNetwork(this)) {
            ToastUtil.show(this, "网络连接失败");
            return;
        }

        loadingDialog.show();
        AddressIdBean bean = new AddressIdBean();
        bean.province = province;
        bean.city = city;
        bean.district = district;
        Api.api_service.getAddressId(bean).compose(RxLifeUtil.checkOn(this)).
                doFinally(() -> {
                    try {
                        loadingDialog.dismiss();
                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(result -> {
                    String resultAddress = province + city + district;

                    event.result = resultAddress;
                    event.provinceId = result.datas.province_id;
                    event.cityId = result.datas.city_id;
                    event.areaId = result.datas.district_id;
                    txtArea.setText(resultAddress);
                });
    }


    @Override
    public void activate(OnLocationChangedListener listener) {
        mListener = listener;
        mLocationClient.startLocation();
    }

    @Override
    public void deactivate() {
        mListener = null;
        if (mLocationClient != null) {
            mLocationClient.stopLocation();
            mLocationClient.onDestroy();
        }
        mLocationClient = null;
    }

    @Override
    public void onCameraChange(CameraPosition cameraPosition) {
    }

    @Override
    public void onCameraChangeFinish(CameraPosition cameraPosition) {
        latlng = cameraPosition.target;
        aMap.clear();
        aMap.addMarker(new MarkerOptions().position(latlng));

        doRePlace();
    }

    @Override
    public void onPoiSearched(PoiResult result, int rCode) {
        if (rCode == 1000) {
            if (result != null && result.getQuery() != null) {// 搜索poi的结果
                if (result.getQuery().equals(query)) {// 是否是同一条
                    poiResult = result;
                    poiItems = poiResult.getPois();// 取得第一页的poiitem数据，页数从数字0开始
                    List<SuggestionCity> suggestionCities = poiResult
                            .getSearchSuggestionCitys();
//                    if (poiItems != null && poiItems.size() > 0) {
//                        for (int i = 0; i < poiItems.size(); i++) {
//                            Log.i("dasdasddsaas", poiItems.get(i).toString());
//                        }
//
////                        adapter = new PoiSearch_adapter(this, poiItems);
////                        mapList.setAdapter(new ArrayAdapter<PoiItem>(this, android.R.layout.simple_list_item_1, poiItems));
////                        mapList.setOnItemClickListener(new mOnItemClickListener());
//                    }
                    if (poiItems != null && poiItems.size() > 0) {
//                        Log.i("doSearchQuery", "执行1");
                        aMap.clear();// 清理之前的图标
                        PoiOverlay poiOverlay = new PoiOverlay(aMap, poiItems);
                        poiOverlay.removeFromMap();
                        poiOverlay.addToMap();
                        poiOverlay.zoomToSpan();
                    } else if (suggestionCities != null
                            && suggestionCities.size() > 0) {
//                        Log.i("doSearchQuery", "执行2");
//                        showSuggestCity(suggestionCities);
                    } else {
//                        不做处理
//                        Log.i("doSearchQuery", "执行3");
                    }


                } else {

                }
            }
        } else {
            Log.i("doSearchQuery", rCode + "错误码");
        }
    }

    @Override
    public void onPoiItemSearched(PoiItem poiItem, int i) {
    }

    //-------- 定位 End ------
    @Override
    protected void onResume() {
        super.onResume();
        mapView.onResume();
        mLocationClient.startLocation();
    }

    @Override
    protected void onPause() {
        super.onPause();
        mapView.onPause();
        mLocationClient.stopLocation();
    }

    @Override
    protected void onDestroy() {
        mLocationClient.onDestroy();
        mapView.onDestroy();
        unbiner.unbind();
        super.onDestroy();
    }

    @Override
    public void onRegeocodeSearched(RegeocodeResult result, int code) {
        if (result != null && result.getRegeocodeAddress() != null
                && result.getRegeocodeAddress().getFormatAddress() != null) {
            addressName = result.getRegeocodeAddress().getFormatAddress();
//            aMap.animateCamera(CameraUpdateFactory.newLatLngZoom(
//                    AMapUtil.convertToLatLng(latLonPoint), 15));
//            regeoMarker.setPosition(AMapUtil.convertToLatLng(latLonPoint));
//            ToastUtil.show(New_LocalActivity.this, addressName);
            int index = addressName.indexOf(result.getRegeocodeAddress().getTownship());

            if (index == 0) {
                editSearch.setText(addressName);
            } else {
                editSearch.setText(result.getRegeocodeAddress().getFormatAddress().substring(index));
            }
            lat = result.getRegeocodeQuery().getPoint().getLatitude() + "";
            lng = result.getRegeocodeQuery().getPoint().getLongitude() + "";
//            获取省市区
//            if (result.getRegeocodeAddress().getProvince().equals(result.getRegeocodeAddress().getCity())) {
//                txtArea.setText(result.getRegeocodeAddress().getCity() + result.getRegeocodeAddress().getDistrict());
//            } else {
//                txtArea.setText(result.getRegeocodeAddress().getProvince() + result.getRegeocodeAddress().getCity() + result.getRegeocodeAddress().getDistrict());
//            }

//            Log.i("dadasdsad","building="+result.getRegeocodeAddress().getBuilding()+"\ngetNeighborhood"+result.getRegeocodeAddress().getNeighborhood()+"\ngetTownship"+result.getRegeocodeAddress().getTownship());
        } else {
            ToastUtil.show(New_LocalActivity.this, "解析失败");
        }
    }

    @Override
    public void onGeocodeSearched(GeocodeResult geocodeResult, int code) {
//        Log.e("sssssssssss", code + "");
        if (code == 1000) {
            if (geocodeResult != null && geocodeResult.getGeocodeAddressList() != null &&
                    geocodeResult.getGeocodeAddressList().size() > 0) {

                GeocodeAddress geocodeAddress = geocodeResult.getGeocodeAddressList().get(0);
                double latitude = geocodeAddress.getLatLonPoint().getLatitude();//纬度
                double longititude = geocodeAddress.getLatLonPoint().getLongitude();//经度
                String adcode = geocodeAddress.getAdcode();//区域编码


//                Log.e("sssssssssss", geocodeAddress.getAdcode() + "");
//                Log.e("sssssssssss", latitude + "");
//                Log.e("sssssssssss", longititude + "");

            } else {
                ToastUtil.makeText(this, "发生错误");
            }
        }
    }

    @OnClick({R.id.btn_back, R.id.txt_right, R.id.btn_area_select, R.id.btn_location})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_back:
                finish();
                break;
            case R.id.txt_right:
                if (TextUtils.isEmpty(UI.toString(txtArea))) {
                    ToastUtil.makeText(this, "请手动选择省市区");
                }
                if (TextUtils.isEmpty(UI.toString(editSearch))) {
                    ToastUtil.makeText(this, "详细地址不能为空");
                }
                setEvent();
                break;
            case R.id.btn_area_select:
//                ToastUtil.makeText(this, UI.toString(editSearch));
                showDialog();
                break;
            case R.id.btn_location:
                aMap.animateCamera(CameraUpdateFactory.newLatLngZoom(firstLatlng, 14), 1000, null);
//                mLocationClient.startLocation();
                break;
        }
    }

    private void setEvent() {

        event.addressDetail = UI.toString(editSearch);
        EventBus.getDefault().post(event);
        finish();
    }

    private void showDialog() {
        selectAreaDialog.show();
    }

    @Override
    public void onAddressSelect(String provinceId, String provinceName, String cityId, String cityName, String areaId, String areaName) {
        String result = (TextUtils.isEmpty(provinceName) ? "" : provinceName) + (TextUtils.isEmpty(cityName) ? "" : cityName) + (TextUtils.isEmpty(areaName) ? "" : areaName);
        txtArea.setText(result);

        searchPlace = result;
        event.provinceId = provinceId;
        event.provinceName = provinceName;
        event.cityId = cityId;
        event.cityName = cityName;
        event.areaId = areaId;
        event.areaName = areaName;
        event.result = result;
        doSearchQuery();
    }


    private class mOnItemClickListener implements AdapterView.OnItemClickListener {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            Intent intent = new Intent();
            intent.putExtra(KEY_LAT, poiItems.get(position).getLatLonPoint().getLatitude());
            intent.putExtra(KEY_LNG, poiItems.get(position).getLatLonPoint().getLongitude());
            intent.putExtra(KEY_DES, poiItems.get(position).getTitle());
            setResult(RESULT_OK, intent);
            finish();
        }
    }
}
